<?php 
header('Content-Type:text/html; charset=utf-8');
$type = isset($_GET['type']) ? $_GET['type'] : 0;
include_once dirname(__FILE__) . "/Snoopy.class.php";
include_once dirname(__FILE__) . "/config.php";

$path = $tablename = '';
switch ($type) {
    case 1: //房产
        $path = 'http://quotes.money.163.com/data/sort/item=ZJ,key=SYMBOL,page=1,count=200,node=05,orderStyle=ASC.html';
        $tablename = 'house';
        break;
    case 2: //金融
        $path = "http://quotes.money.163.com/data/sort/item=ZI,key=SYMBOL,page=1,count=200,node=05,orderStyle=ASC.html";
        $tablename = 'bank';
        break;
    case 3: //计算机
        $path = "http://quotes.money.163.com/data/sort/item=ZG83,key=SYMBOL,page=1,count=200,node=05,orderStyle=ASC.html";
        $tablename = 'computer';
        break;
    case 4: //金属钢铁
        $path = "http://quotes.money.163.com/data/sort/item=ZC65,key=SYMBOL,page=1,count=200,node=05,orderStyle=ASC.html";
        $tablename = 'steel';
        break;
    default:
        $path = 'http://quotes.money.163.com/data/sort/item=ZJ,key=SYMBOL,page=1,count=200,node=05,orderStyle=ASC.html';
        $tablename = 'house';
}

function dealMessCode($s){
    $s = trim(str_replace(array('dataArr1 = ','diy.loadDataFinish1();',';','\''),array('','','','"'),$s));
    //$s = preg_replace('/(-?[^\D]+\.?[^\D]+)E(-\d+)/','"$1E$2"',$s);
    $s = preg_replace('/(-?[^\D]+\.?[^\D]*)E(-\d+)/', 0, $s);
    $s = iconv("GB2312", "UTF-8", $s);
    return $s;
}

function myCurl ($url)
{
    $headers[] = 'Host:quotes.money.163.com';
    $headers[] = 'Connection: Keep-Alive';
    $headers[] = 'Referer: http://quotes.money.163.com/market/diy.html';
    $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)";
    $process = curl_init($url);
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($process, CURLOPT_HEADER, 0);
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
    curl_setopt($process, CURLOPT_TIMEOUT, 30);
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
    $return = curl_exec($process);
    curl_close($process);
    return $return;
}

function mySnoopy ($url)
{
    $snoopy = new Snoopy();
    $snoopy->proxy_host = "quotes.money.163.com";
    $snoopy->agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 ( .NET CLR 3.5.30729)";
    $snoopy->referer = "http://quotes.money.163.com/market/diy.html";
    if ($snoopy->fetch($url)) {
        $s = $snoopy->results;
    } else {
        echo "error fetching document: " . $snoopy->error . "\n";
    }
    return $s;
}
$date = date('Y-m-d');
$mysqli = new mysqli($dbConf['host'], $dbConf['username'], $dbConf['passwd'], $dbConf['dbname']);
if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
}
$sql = "select count(1) from $tablename where rdate = '$date'";
if ($result = $mysqli->query($sql)) {
    while ($row = $result->fetch_row()) {
        if ($row[0] > 0) {
            $result->close();
            exit('今日数据已经保存于数据库，请勿重复保存！');
        }
    }
    $result->close();
} 
//$s = file_get_contents($path);
$s = mySnoopy($path);
$data = json_decode(dealMessCode($s));
if (count($data) == 0) {
    $s = myCurl($path);
    $data = json_decode(dealMessCode($s));
    if (count($data) == 0) {
        exit('不好! 数据是空的...');
    }
}

//剔除B股
$aData = array();
foreach ($data as $k => $v) {
    if (strpos($v[1], 'B') === false) {
        $aData[] = $v;
    }
}
$aCount = count($aData);
    //记录于数据库中
foreach ($aData as $k => $v) {
    array_pop($v);
    $cols = "'" . implode("','", $v) . "'";
    $sql = "insert into $tablename values(null,$cols,'$date')";
    if ($r = $mysqli->query($sql)) {
        //$r->close();
    }
}
$mysqli->close();
exit('保存数据库成功.');